<script setup>
import { defineProps, defineEmits, ref, onMounted } from 'vue';
// 导入QuillEditor富文本编辑器组件
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css'; // 导入样式

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  categories: {
    type: Array,
    required: true
  }
});

const emit = defineEmits(['close', 'create-post']);

const newPost = ref({
  title: '',
  content: '', // 将在API调用时转换为richContent
  category: 'general',
});

const isSubmitting = ref(false);
const error = ref('');
const imageUploadMessage = ref('');

// 图片上传限制配置
const imageConfig = {
  maxWidth: 1200, // 最大宽度，单位像素
  maxHeight: 1200, // 最大高度，单位像素
  maxSize: 2, // 最大文件大小，单位MB
  quality: 0.8 // 压缩质量
};

// 处理图片上传
const handleImageUpload = function() {
  const input = this.container.querySelector('input.ql-image[type=file]');
  
  if (input) {
    // 移除旧的监听器
    input.removeEventListener('change', handleFileChange);
    
    // 添加新的监听器
    input.addEventListener('change', handleFileChange);
  }
};

// 处理文件选择事件
const handleFileChange = (e) => {
  imageUploadMessage.value = '';
  const file = e.target.files[0];
  
  // 检查文件类型
  if (!file.type.match(/^image\/(jpeg|png|gif|webp|jpg)$/)) {
    imageUploadMessage.value = '只能上传图片文件(.jpg, .png, .gif, .webp)';
    e.target.value = '';
    return;
  }
  
  // 检查文件大小
  const fileSizeMB = file.size / (1024 * 1024);
  if (fileSizeMB > imageConfig.maxSize) {
    imageUploadMessage.value = `图片大小不能超过${imageConfig.maxSize}MB`;
    e.target.value = '';
    return;
  }
  
  // 创建图片对象并处理图片
  const img = new Image();
  img.onload = () => {
    // 检查图片尺寸
    if (img.width > imageConfig.maxWidth || img.height > imageConfig.maxHeight) {
      // 创建Canvas进行缩放
      const canvas = document.createElement('canvas');
      let width = img.width;
      let height = img.height;
      
      // 计算缩放比例
      if (width > imageConfig.maxWidth) {
        const ratio = imageConfig.maxWidth / width;
        width = imageConfig.maxWidth;
        height = height * ratio;
      }
      
      if (height > imageConfig.maxHeight) {
        const ratio = imageConfig.maxHeight / height;
        height = imageConfig.maxHeight;
        width = width * ratio;
      }
      
      canvas.width = width;
      canvas.height = height;
      
      // 将图片绘制到Canvas上，实现缩放
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, width, height);
      
      // 转换为Blob对象
      canvas.toBlob((blob) => {
        const resizedFile = new File([blob], file.name, {
          type: file.type,
          lastModified: Date.now()
        });
        
        // 上传处理后的图片
        uploadImage(resizedFile);
      }, file.type, imageConfig.quality);
      
      imageUploadMessage.value = '图片已自动调整大小';
    } else {
      // 如果图片尺寸符合要求，直接上传
      uploadImage(file);
    }
  };
  
  // 设置图片源
  img.src = URL.createObjectURL(file);
};

// 上传图片方法
const uploadImage = (file) => {
  // 这里应当实现上传逻辑，但目前使用本地URL模拟
  const url = URL.createObjectURL(file);
  
  // 获取QuillEditor实例
  const quill = document.querySelector('.ql-editor').parentElement.__vue__;
  
  // 获取当前光标位置
  const range = quill.getSelection();
  
  // 在光标位置插入图片
  quill.insertEmbed(range.index, 'image', url);
  
  // 将光标移动到图片后
  quill.setSelection(range.index + 1);
};

// 富文本编辑器配置
const editorOptions = {
  theme: 'snow',
  modules: {
    toolbar: {
      container: [
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
        [{ 'color': [] }, { 'background': [] }],
        ['link', 'image'],
        ['clean']
      ],
      handlers: {
        image: handleImageUpload
      }
    }
  },
  placeholder: '分享您的想法、问题或经历...'
};

const createPost = async () => {
  if (newPost.value.title.trim() && newPost.value.content.trim()) {
    isSubmitting.value = true;
    error.value = '';
    
    try {
      await emit('create-post', { ...newPost.value });
      
      // 重置表单
      newPost.value = {
        title: '',
        content: '',
        category: 'general'
      };
    } catch (err) {
      error.value = '创建帖子失败，请稍后再试';
      console.error('创建帖子出错:', err);
    } finally {
      isSubmitting.value = false;
    }
  } else {
    error.value = '请填写标题和内容';
  }
};

const closeModal = () => {
  if (!isSubmitting.value) {
    error.value = '';
    emit('close');
  }
};
</script>

<template>
  <div class="create-post-modal" v-if="show">
    <div class="modal-overlay" @click="closeModal"></div>
    <div class="modal-container">
      <div class="modal-header">
        <h3 class="modal-title">创建新主题</h3>
        <button class="modal-close" @click="closeModal" :disabled="isSubmitting">×</button>
      </div>
      
      <div class="modal-body">
        <div class="form-group">
          <label for="post-title">标题</label>
          <input 
            type="text" 
            id="post-title" 
            v-model="newPost.title" 
            placeholder="输入主题标题..."
            class="form-control"
            :disabled="isSubmitting"
          >
        </div>
        
        <div class="form-group">
          <label for="post-category">分类</label>
          <select id="post-category" v-model="newPost.category" class="form-control" :disabled="isSubmitting">
            <option v-for="category in categories.filter(c => c.id !== 'all')" :key="category.id" :value="category.id">
              {{ category.icon }} {{ category.name }}
            </option>
          </select>
        </div>
        
        <div class="form-group">
          <label for="post-content">内容</label>
          <!-- 使用富文本编辑器替换普通文本区域 -->
          <QuillEditor
            v-model:content="newPost.content"
            :options="editorOptions"
            contentType="html"
            :disabled="isSubmitting"
            class="editor-container"
          />
          <div v-if="imageUploadMessage" class="image-message">
            <span class="image-message-icon">ℹ️</span>
            {{ imageUploadMessage }}
          </div>
          <div class="editor-tips">
            提示：图片大小不超过2MB，宽高不超过1200像素，超过限制将自动缩放
          </div>
        </div>
        
        <div v-if="error" class="error-message">
          {{ error }}
        </div>
      </div>
      
      <div class="modal-footer">
        <button class="modal-cancel" @click="closeModal" :disabled="isSubmitting">取消</button>
        <button class="modal-submit" @click="createPost" :disabled="isSubmitting">
          <span v-if="isSubmitting" class="spinner"></span>
          <span>{{ isSubmitting ? '发布中...' : '发布主题' }}</span>
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 创建新帖子弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
  backdrop-filter: blur(3px);
}

.modal-container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 90%;
  max-width: 800px; /* 增加宽度以适应编辑器 */
  max-height: 90vh; /* 限制最大高度 */
  overflow-y: auto; /* 添加滚动条 */
  background-color: white;
  border-radius: 10px;
  z-index: 101;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  animation: modalFadeIn 0.3s forwards;
}

.modal-header {
  position: sticky;
  top: 0;
  background-color: white;
  padding: 20px 25px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 1;
}

.modal-title {
  font-size: 1.3rem;
  color: #333;
  margin: 0;
}

.modal-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #999;
  transition: color 0.3s;
}

.modal-close:hover:not(:disabled) {
  color: #333;
}

.modal-close:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.modal-body {
  padding: 25px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group:last-child {
  margin-bottom: 0;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-control {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  font-size: 1rem;
  transition: all 0.3s;
}

.form-control:focus:not(:disabled) {
  border-color: #00c389;
  box-shadow: 0 0 0 3px rgba(0, 195, 137, 0.1);
}

.form-control:disabled {
  background-color: #f9f9f9;
  cursor: not-allowed;
}

/* 富文本编辑器样式 */
.editor-container {
  border-radius: 5px;
  overflow: hidden;
  min-height: 200px;
}

.editor-tips {
  margin-top: 8px;
  font-size: 0.85rem;
  color: #888;
  font-style: italic;
}

.image-message {
  margin-top: 8px;
  padding: 6px 10px;
  background-color: #f0f8ff;
  border-radius: 4px;
  color: #0066cc;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
}

.image-message-icon {
  margin-right: 6px;
}

/* 让编辑器在禁用状态下有明显的视觉提示 */
:deep(.ql-container.ql-disabled) {
  background-color: #f9f9f9;
}

:deep(.ql-toolbar) {
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  background-color: #f9f9f9;
}

:deep(.ql-container) {
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
}

:deep(.ql-editor img) {
  max-width: 100%;
  max-height: 500px;
  object-fit: contain;
}

.error-message {
  color: #e74c3c;
  font-size: 0.9rem;
  padding: 8px 12px;
  background-color: #fef2f2;
  border-radius: 5px;
  margin-top: 15px;
}

.modal-footer {
  position: sticky;
  bottom: 0;
  background-color: white;
  padding: 20px 25px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  z-index: 1;
}

.modal-cancel {
  padding: 10px 20px;
  background-color: #f8f8f8;
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.3s;
}

.modal-cancel:hover:not(:disabled) {
  background-color: #f0f0f0;
}

.modal-cancel:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.modal-submit {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 25px;
  background-color: #00c389;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.modal-submit:hover:not(:disabled) {
  background-color: #00a873;
}

.modal-submit:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.spinner {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255,255,255,0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s ease-in-out infinite;
  margin-right: 8px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

@keyframes modalFadeIn {
  0% {
    opacity: 0;
    transform: translate(-50%, -48%);
  }
  100% {
    opacity: 1;
    transform: translate(-50%, -50%);
  }
}
</style> 